package com.longan.common.filter;

import com.alibaba.fastjson.JSON;
import com.longan.common.constant.GatewayFilterConstant;
import com.longan.common.utils.AjaxResult;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.PrintWriter;

public class GatewayFilter implements Filter {

    private void returnJson(ServletResponse response, String json) throws IOException {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        PrintWriter writer = response.getWriter();
        writer.print(json);

    }

    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        String gateway = request.getHeader(GatewayFilterConstant.FILTER_KEY_NAME);
        if (gateway == null || gateway.equals("") || !gateway.equals(GatewayFilterConstant.FILTER_KEY_SECRET)) {
            returnJson(servletResponse, JSON.toJSONString(AjaxResult.error("你这是非法访问！")));
            return;
        }
        filterChain.doFilter(servletRequest, servletResponse);
    }
}
